import logging

from pylons import config
from pymomail.lib.base import *
from pylons.controllers.util import redirect_to

log = logging.getLogger(__name__)

class MailUserController(BaseController):

    def index(self):
        # Return a rendered template
        #   return render('/some/template.mako')
        # or, Return a response
        return 'Hello World'

    def login(self, format='wml'):
        username = ''
        password = ''

        # Process posted data

        ### domains work like this.
        ### IF there is no login_domain config entry, then the domain must be provided in the username.
        ### IF login_domains is defined, but contains only one domain then that domain is appended to the username.
        ### IF login_domains is defined with more than one domain then the domain is used if present in the config.
        ### So, the domain form field must be provided if the login_domains contains multiple names.
        ### At the end of this, domain will be blank, or a string like @example.com

        domain = ''

        try:
            domain = request.params['domain']
        except KeyError:
            pass

        try:
            if len(config['login_domains'].split()) == 1:
                domain = ''.join(['@',config['login_domains']])
            else:
                if domain.strip() in config['login_domains'].split():
                    domain = ''.join(['@',domain])
        except KeyError:
            pass

        session['domain'] = domain

        try:
            username = request.params['username']
            password = request.params['password']
            session['username'] = username
            session['password'] = password
            session.save()
            return redirect_to(controller='folder', action='view')

        except KeyError:
            pass

        try:
            c.default_domain = config['default_domain']
        except KeyError:
            pass

        c.domains = config['login_domains'].split()
        c.username = username
        response.headers['Content-type'] = "text/vnd.wap.wml"
        return render('/wml/login.mako')

    def logout(self, format='wml'):
        response.headers['Content-type'] = "text/vnd.wap.wml"
        return render('/wml/logout.mako')

    def settings(self, format='wml'):
        response.headers['Content-type'] = "text/vnd.wap.wml"
        return render('/wml/settings.mako')
